/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.network.miscellaneous.map;

import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import twaver.TWaverUtil;

public class MapXMLUtil {
	
	public static List parserXml(String fileName, int xoffset, int yoffset) {
	
		List list = new ArrayList();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputStream is = TWaverUtil.getInputStream(fileName);
			Document document = db.parse(is);
			NodeList features = document.getElementsByTagName("f");
			int count = features.getLength();
			for (int i = 0; i < count; i++) {
				Node feature = features.item(i);
				MapNode stateNode = new MapNode();
				list.add(stateNode);
				List segments = new ArrayList();
				for (Node node = feature.getFirstChild(); node != null; node = node.getNextSibling()) {
					if (node.getNodeType() == Node.ELEMENT_NODE) {
						if ("na".equals(node.getNodeName())) {
							for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
								if (child.getNodeType() == Node.ELEMENT_NODE) {
									String n = child.getAttributes().getNamedItem("n").getNodeValue();
									String v = child.getAttributes().getNamedItem("v").getNodeValue();
									stateNode.putClientProperty(n, v);
								}
							}
						}
						if ("s".equals(node.getNodeName())) {
							for (Node children = node.getFirstChild(); children != null; children = children.getNextSibling()) {
								if (children.getNodeType() == Node.ELEMENT_NODE) {
									Node segment = children.getAttributes().getNamedItem("s");
									String x = children.getAttributes().getNamedItem("x").getNodeValue();
									String y = children.getAttributes().getNamedItem("y").getNodeValue();
									stateNode.addPoint(new Point2D.Double(Double.parseDouble(x)+xoffset, Double.parseDouble(y)+yoffset));
									if (segment != null) {
										segments.add(new Integer(PathIterator.SEG_MOVETO));
									} else {
										segments.add(new Integer(PathIterator.SEG_LINETO));
									}
								}
							}
						}
						stateNode.setSegments(segments);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}